var pre = "";
var next = "";
var code = "";
var keyArr = [];
var num = 0;
var codeLink = "";
var target = "";
$(function () {
    setBgAndFont();
    getReadInfo(false);
    getPresentConfig();
    $(".left-wrapper").click(function () {
        // 判断是否加入书架
        isShelf();
    });
    $(".home-wrapper").click(function () {
        location.href = "../index.html?channel="+getQueryString("channel");
    });
    $(".bg").click(function () {
        $(this).addClass("active").siblings(".bg").removeClass("active");
        $("body").removeClass().addClass($(this).attr("data-bg"));
        // 将选择的背景色存到缓存
        localStorage.setItem("bgColor",$(this).attr("data-bg"));
        // 夜间模式单独设置下面目录按钮样式
        if($(this).hasClass("evening")){
            $(".catalog-btn .icon-wrapper").addClass("dark");
            $('.bottom-wrapper .border-1px-all').addClass("dark");
        }else{
            $(".catalog-btn .icon-wrapper").removeClass("dark");
            $('.bottom-wrapper .border-1px-all').removeClass("dark");
        }
    });
    $(".pre-chap-wrapper").click(function () {
        if(pre == ""){
            Toast("已经到头了");
        }else{
            location.href = "./read.html?id="+getQueryString("id")+"&cid="+pre+"&channel="+getQueryString("channel");
        }
    });
    $(".next-chap-wrapper").click(function () {
        if(next == ""){
            Toast("已经到头了");
        }else{
            location.href = "./read.html?id="+getQueryString("id")+"&cid="+next+"&channel="+getQueryString("channel");
        }
    });
    $(".catalog-btn").click(function () {
        location.href = "./catalog.html?id="+getQueryString("id")+"&current="+getQueryString("cid")+"&channel="+getQueryString("channel");
    });

    // 打赏
    $(".present").click(function () {
        $(".select-present-mask").show();
    });

    $(".select-present-top-mask").click(function (e) {
        $(".select-present-mask").hide();
    });

    $(".present-list").on("click","li",function () {
        $(this).addClass("selected").siblings("li").removeClass("selected");
        $(this).children(".border-line").show();
        $(this).siblings("li").children(".border-line").hide();
    });

    $(".add-shelf-wrapper .cancel").click(function () {
        $(".add-shelf-wrapper").hide();
        location.href = "./detail.html?id="+getQueryString("id")+"&channel="+getQueryString("channel");
    });
    $(".sign-success-wrapper").click(function () {
        $(this).hide();
        popModel(num);
    });
    $(".onsell-price-wrapper .cancel").click(function () {
        $(".onsell-price-wrapper").hide();
        popModel(num);
    });
    $(".close-focus").click(function () {
        $(".focus-wx-wrapper").hide();
        popModel(num);
    });
    $(".focus-btn").click(function () {
        location.href = codeLink;
    });
    $(".close-first-charge").click(function () {
        $(".first-charge-wrapper").hide();
        popModel(num);
    });
    $(".get-first-charge").click(function () {
        // 首充或者充值30
        goCharge();
    });
    $(".close-charge-30").click(function () {
        $(".charge-30-wrapper").hide();
        popModel(num);
    });
    $(".close-vip-btn").click(function () {
        $(".vip-wrapper").hide();
        popModel(num);
    });
});

function getReadInfo(isAgain) {
    $.ajax({
        type:'get',
        url:BASE_URl + "chap/read?id="+getQueryString("cid"),
        success:function (data) {
            if(data.success){
                $(".left-wrapper").html(data.data.name);
                pre = data.data.pre;
                next = data.data.next;
                // 弹框数组
                keyArr = data.data.push_info.split(",");
                if(!isAgain){
                    if (keyArr[0] != "") {
                        // 开始弹框
                        popModel(num);
                    }
                }
                if(data.data.visible == "success"){
                    $(".should-recharge-wrapper").hide();
                    getReadContent(data.data.url);
                }
                // VIP权限：B100011
                if(data.data.visible == "B100011"){
                    $(".should-recharge-wrapper").show();
                    $(".set-options-wrapper").hide();
                    $(".read-content").hide();
                    var html = `<div class="big-chap-name tc">${data.data.name}</div>
                                <p class="unlock-tip tc">——支持作者，解锁后继续阅读——</p>
                                <p class="vip-tip tc">本章为VIP章节，VIP用户专享</p>
                                <div class="recharge-btn tc become-vip" onclick="goPath('vip')">成为VIP</div>`;
                    $(".should-recharge-wrapper").html(html);
                }
                // 单本购买权限：B100012
                if(data.data.visible == "B100012"){
                    // $(".onsell-price-wrapper").show();
                    // $(".should-recharge-wrapper").show();
                    // $(".set-options-wrapper").hide();
                    // $(".read-content").hide();
                    // var html = `<div class="big-chap-name tc">${data.data.name}</div>
                    //             <p class="unlock-tip tc">——支持作者，解锁后继续阅读——</p>
                    //             <p class="limit-price tc">本书籍限时特价！全本仅需<span class="now-price">${data.data.book_sell_price}</span>书币 <s class="orgin-price">${data.data.book_original_price}书币</s></p>`;
                    // $(".should-recharge-wrapper").html(html);
                    $(".now-price").html(data.data.book_sell_price);
                    $(".origin-price").html(data.data.book_original_price);
                    $(".onsell-price-wrapper").show();
                }
                // 书币不足：U100004
                if(data.data.visible == "U100004"){
                    $(".should-recharge-wrapper").show();
                    $(".set-options-wrapper").hide();
                    $(".read-content").hide();
                    var html = `<div class="big-chap-name tc">${data.data.name}</div>
                                <p class="unlock-tip tc">——支持作者，解锁后继续阅读——</p>
                                <div class="need-wrapper tc">
                                    本章解锁：<span class="price">${data.data.price}</span>书币&nbsp;&nbsp;&nbsp;&nbsp;书币余额：<span class="rest">${data.data.user_coin}</span>书币
                                </div>
                                <div class="recharge-btn tc" onclick="goPath('recharge')">余额不足，立即充值</div>
                                <p class="join-vip tc">加入VIP，畅读全站小说</p>`;
                    $(".should-recharge-wrapper").html(html);
                }
                // 书券不足：U100005
                if(data.data.visible == "U100005"){
                    $(".should-recharge-wrapper").show();
                    $(".set-options-wrapper").hide();
                    $(".read-content").hide();
                    var html = `<div class="big-chap-name tc">${data.data.name}</div>
                                <p class="unlock-tip tc">——支持作者，解锁后继续阅读——</p>
                                <div class="need-wrapper tc">
                                    本章解锁：<span class="price">${data.data.price}</span>书券&nbsp;&nbsp;&nbsp;&nbsp;书券余额：<span class="rest">${data.data.user_gift}</span>书券
                                </div>
                                <div class="recharge-btn tc" onclick="goPath('exchange')">书券不足，立即获得</div>
                                <p class="get-gift-way">书券获得方式：1.连续每日签到，可获得书券礼包</p>
                                <p class="get-gift-way"><span style="opacity: 0">书券获得方式：</span>2.可用书币兑换书券</p>`;
                    $(".should-recharge-wrapper").html(html);
                }
            }
        }
    });
}

function getReadContent(url) {
    $.ajax({
        type:'get',
        url:url,
        dataType: 'text',
        success:function (data) {
            $(".read-content").html(data.data);
        }
    });
}

function setBgAndFont() {
    // 读取缓存里的背景色和字体大小并设置
    var bgColor = localStorage.getItem("bgColor");
    var size = localStorage.getItem("size");
    if(bgColor){
        $("."+bgColor).addClass("active").siblings(".bg").removeClass("active");
        $("body").removeClass().addClass(bgColor);
        if(bgColor == "evening"){
            $(".catalog-btn .icon-wrapper").addClass("dark");
            $('.bottom-wrapper .border-1px-all').addClass("dark");
        }else{
            $(".catalog-btn .icon-wrapper").removeClass("dark");
            $('.bottom-wrapper .border-1px-all').removeClass("dark");
        }
    }
    if(size){
        $(".read-content").css("font-size",size);
    }
}

function changeFontSize(type) {
    var size = parseInt($(".read-content").css("font-size"));
    if(type == "enlarge"){
        switch (size) {
            case 12:
                $(".read-content").css("font-size","15px");
                localStorage.setItem("size","15px");
                break;
            case 15:
                $(".read-content").css("font-size","17px");
                localStorage.setItem("size","17px");
                break;
            case 17:
                $(".read-content").css("font-size","19px");
                localStorage.setItem("size","19px");
                break;
            case 19:
                $(".read-content").css("font-size","23px");
                localStorage.setItem("size","23px");
                break;
            case 23:
                $(".read-content").css("font-size","25px");
                localStorage.setItem("size","25px");
                break;
            case 25:
                Toast("不能再大了哦");
                break;
        }
    }else if(type == "reduce"){
        switch (size) {
            case 12:
                Toast("不能再小了哦");
                localStorage.setItem("size","15px");
                break;
            case 15:
                $(".read-content").css("font-size","12px");
                localStorage.setItem("size","12px");
                break;
            case 17:
                $(".read-content").css("font-size","15px");
                localStorage.setItem("size","15px");
                break;
            case 19:
                $(".read-content").css("font-size","17px");
                localStorage.setItem("size","17px");
                break;
            case 23:
                $(".read-content").css("font-size","19px");
                localStorage.setItem("size","19px");
                break;
            case 25:
                $(".read-content").css("font-size","23px");
                localStorage.setItem("size","23px");
                break;
        }
    }
}

function getPresentConfig() {
    $.ajax({
        type:'get',
        url:BASE_URl + "config/prop",
        success:function (data) {
            if(data.success){
                DrawPresentConfig(data.data);
            }
        }
    });
}

function DrawPresentConfig(data) {
    var html = "";
    for(var i = 0;i < data.prop.length;i ++){
        html += `
                <li class="border-1px-all" data-id="${data.prop[i].id}">
                    <div class="present-item">
                        <div class="present-img"><img src="${data.prop[i].image}" alt="" width="100%" height="100%"></div>
                        <div class="present-name tc">${data.prop[i].name}</div>
                        <div class="present-price tc">${data.prop[i].price}</div>
                    </div>
                    <div class="border-line"></div>
                </li>
        `;
    }
    $(".select-present-wrapper .present-list").html(html);
    $(".rest-coin span").html(data.coin);
}

function givePresent() {
    var present = $(".present-list li.selected");
    if(present.length == 0){
        Toast("请先选择您要打赏的礼物");
    }else{
        var propId = present[0].dataset.id;
        $.ajax({
            type:'get',
            url:BASE_URl + "user/prop/send?book=" + getQueryString("id") + "&prop=" + propId,
            success:function (data) {
                if(data.success){
                    Toast("打赏成功");
                    $(".select-present-mask").hide();
                }
            }
        });
    }
}

function isShelf() {
    $.ajax({
        type:'get',
        url:BASE_URl + "book/in/fav?id=" + getQueryString("id"),
        success:function (data) {
            if(data.success){
                if(data.data){
                    location.href = "./detail.html?id="+getQueryString("id")+"&channel="+getQueryString("channel");
                }else{
                    $(".add-shelf-wrapper").show();
                }
            }
        }
    });
}

function addShelf() {
    $.ajax({
        type:'get',
        url:BASE_URl + "book/fav?id=" + getQueryString("id"),
        success:function (data) {
            if(data.success){
                Toast("已加入书架");
                setTimeout(function () {
                    location.href = "./detail.html?id="+getQueryString("id")+"&channel="+getQueryString("channel");
                },1000)
            }
        }
    });
}

function buyBook() {
    $.ajax({
        type:'get',
        url:BASE_URl + "book/buy?id=" + getQueryString("id"),
        success:function (data) {
            if(data.success){
                Toast("购买成功");
                setTimeout(function () {
                    location.reload();
                },1000)
            }else{
                if (data.data.ercode == "U100004") {
                    Toast("书币余额不足");
                } else {
                    Toast(data.data.ercode);
                }
            }
        }
    });
}

function goPath(path) {
    location.href = "./"+path+".html?channel="+getQueryString("channel");
}

function sign() {
    $.ajax({
        type:'get',
        url:BASE_URl + "user/sign/daily",
        success:function (data) {
            if(data.success){
                var html = "";
                if(data.data.gift == 0){
                    html = `<div class="success-title tc">恭喜你签到成功</div><div class="success-award tc">获得${data.data.coin}书币</div>`;
                }else{
                    html = `<div class="success-title tc">恭喜你签到成功</div><div class="success-award tc">获得200书币+${data.data.gift}书券</div>`;
                }
                $(".success-detail").html(html);
                $(".sign-success-wrapper").show();
            }
        }
    });
}

function popModel(i) {
    $.ajax({
        type:'get',
        url:BASE_URl + "push/info?key="+keyArr[i],
        success:function (data) {
            if(data.success){
                num ++;
                if (data.data[0].type == "sub_wxmp") {
                    codeLink = data.data[0].url;
                    $(".code-img-wrapper").html(`<img src="${data.data[0].img}" width="100%" height="100%">`);
                    $(".focus-wx-wrapper").show();
                } else if (data.data[0].type == "pay_first" || data.data[0].type == "pay_month_year" || data.data[0].type == "pay_extend" || data.data[0].type == "pay_activity") {
                    code = data.data[0].code;
                    target = data.data[0].target;
                    if (data.data[0].type == "pay_first") {
                        //首充
                        $(".first-charge-wrapper").show();
                    } else {
                        if (data.data[0].type == "pay_month_year") {
                            //包年包月
                           $(".vip-wrapper").show();
                        } else if (data.data[0].type == "pay_extend") {
                            //30
                            $(".charge-30-wrapper").show();
                        }
                    }
                } else if (data.data[0].type == "sign_daily") {
                    //每日签到
                    sign();
                    $(".sign-success-wrapper").show();
                    // 签到后赠送的书币或书券加上余额后是否足以购买章节
                    getReadInfo(true);
                }
            }
        }
    });
}

function openVip(type) {
    if(target == "blank"){
        location.href = "./vip.html?code="+type+"&channel="+getQueryString("channel");
    }else{
        $.ajax({
            type:'get',
            url:BASE_URl + "pay/apply/wechat?code=" + type,
            success:function (data) {
                if(data.success){
                    if (typeof WeixinJSBridge == "undefined") {
                        if (document.addEventListener) {
                            document.addEventListener("WeixinJSBridgeReady",onBridgeReady(), false);
                        } else if (document.attachEvent) {
                            document.attachEvent("WeixinJSBridgeReady", onBridgeReady());
                            document.attachEvent("onWeixinJSBridgeReady",onBridgeReady());
                        }
                    }else {
                        onBridgeReady(data.data);
                    }
                }else{
                    Toast(data.data.ercode);
                }
            }
        })
    }
}

function goCharge() {
    if(target == "blank"){
        location.href = "./recharge.html?code="+code+"&channel="+getQueryString("channel");
    }else{
        $.ajax({
            type:'get',
            url:BASE_URl + "pay/apply/wechat?code=" + code,
            success:function (data) {
                if(data.success){
                    if (typeof WeixinJSBridge == "undefined") {
                        if (document.addEventListener) {
                            document.addEventListener("WeixinJSBridgeReady",onBridgeReady(), false);
                        } else if (document.attachEvent) {
                            document.attachEvent("WeixinJSBridgeReady", onBridgeReady());
                            document.attachEvent("onWeixinJSBridgeReady",onBridgeReady());
                        }
                    }else {
                        onBridgeReady(data.data);
                    }
                }else{
                    Toast(data.data.ercode);
                }
            }
        })
    }
}

// 微信支付
function onBridgeReady(param) {
    WeixinJSBridge.invoke("getBrandWCPayRequest", param, function(res) {
        if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 支付成功
            Toast("支付成功");
            location.reload();
        }
        if (res.err_msg == "get_brand_wcpay_request:cancel") {
            // 取消支付
            Toast("支付已取消");
            $.ajax({
                type:'get',
                url:BASE_URl + "pay/cancel/wechat?orderid=" + param.package.split("=")[1],
                success:function (data) {}
            });
        }
        if (res.err_msg == "get_brand_wcpay_request:fail") {
            // 支付失败
            Toast("支付失败");
        }
    });
}